package com.ebt.m.customer.ui;

import android.content.Context;

import com.ebt.m.AppInitService;
import com.ebt.m.customer.event.EventEmpty;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.commons.buscomponent.listview.BaseListContract;
import com.ebt.m.commons.buscomponent.listview.BaseListPresenter;
import com.ebt.m.data.bean.ProposalListItem;
import com.ebt.m.proposal_v2.bean.event.DraftUpdateCompleteEvent;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.buscomponent.listview.SectionItem;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Damon on 2017/10/31.
 */

public class CustomerProposePresenter extends BaseListPresenter<BaseListContract.IView> {
    @Override
    public List<SectionItem> createSectionItem(List datas) {
        return null;
    }

    private List<SectionItem> items = new ArrayList<>();
    String mCustomerUuid;

    public CustomerProposePresenter(Context context, BaseListContract.IView iView) {
        super(context, iView);
    }

    @Override
    public void loadNew(Object... args) {
        mCustomerUuid = (String) args[0];
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.getProposalListByCustomerId(mCustomerUuid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(result -> {
                    items.clear();
                    List<ProposalListItem> listProposalMsgs = result.getData();
                    if (listProposalMsgs != null && listProposalMsgs.size() > 0) {
                        for (int i = 0; i < listProposalMsgs.size(); i++) {
                            SectionItem sectionItem = new SectionItem(111, listProposalMsgs.get(i));
                            items.add(sectionItem);
                        }
                    }
                })
                .subscribe(sectionItems -> {
                            iView.updateData(items);
                            EventBus.getDefault().post(new EventEmpty(items.size() <= 0)); //计划书为空
                            EventBus.getDefault().post(new DraftUpdateCompleteEvent()); // 关闭建议书编辑页面
                        }
                        , throwable -> {
                            NetUtils.checkHttpException(mContext, throwable);
                            EventBus.getDefault().post(new DraftUpdateCompleteEvent()); // 关闭建议书编辑页面
                            iView.errorData();
                        });
    }

    @Override
    public void refresh() {
        loadNew(mCustomerUuid);
    }

    @Override
    public void loadNext(Object... args) {
    }

}
